import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.googleapis.ajax.common.PagedList;
import com.googleapis.ajax.schema.WebResult;
import com.googleapis.ajax.services.GoogleSearchQueryFactory;
import com.googleapis.ajax.services.WebSearchQuery;
import com.googleapis.ajax.services.enumeration.ResultSetSize;

public class Mp3FinderMain {

	private List<String> addresses = new ArrayList<String>();
	private File outputFile;

	public static void main(String[] args) throws Throwable {
		new Mp3FinderMain().run();
		System.out.println("Done.");
	}

	private void run() throws Throwable {
		findAddresses();
		outputFile();
		openFile();
	}

	private void findAddresses() throws Throwable {
		GoogleSearchQueryFactory factory = GoogleSearchQueryFactory
				.newInstance("applicationKey");

		System.out.println("What title are you looking for ?");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String title = br.readLine();
		String[] sitesNames = { "4shared", "zippyshare", "beemp3" };
		String[] sitesUrls = { "http://www.4shared.com", ".zippyshare.com",
				"http://beemp3.com" };

		for (int i = 0; i < sitesNames.length; i++) {
			WebSearchQuery query = factory.newWebSearchQuery();
			query.withResultSetSize(ResultSetSize.LARGE);
			PagedList<WebResult> response = query.withQuery(
					title + " " + sitesNames[i]).list();
			for (WebResult result : response) {
				if (result.getUrl().contains(sitesUrls[i])) {
					addresses.add(result.getUrl());
				}
			}
		}
		br.close();
	}

	private void outputFile() throws Throwable {
		File outputDir = new File("C:/Temp");
		outputDir.mkdirs();
		outputFile = new File(outputDir, "output.htm");
		BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
		writer.append("<html>\r\n<body>\r\n")
				.append("<style>\r\nbody {\r\ntext-align: center;\r\n)")
				.append("font-size: 35;\r\nfont-family:calibri;\r\n")
				.append("}\r\n</style>\r\n</style>\r\n")
				.append("<br><br><br>\r\n");

		for (int i = 0; i < addresses.size(); i++) {
			writer.append("<a href=\"").append(addresses.get(i)).append("\">")
					.append(addresses.get(i)).append("</a><br>\r\n");
		}
		writer.append("\r\n</body>\r\n</html>");

		writer.close();
	}

	private void openFile() throws Throwable {
		Runtime.getRuntime().exec(
				"explorer \"" + outputFile.getAbsolutePath() + "\"");
	}
}
